﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using UploadPhotoTool.Upload;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        UploadTask task;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDlg = new OpenFileDialog();
            openFileDlg.Multiselect = true;
            if (openFileDlg.ShowDialog() == DialogResult.OK)
            {
                IEnumerable<FileInfo> files = openFileDlg.FileNames.Select(p => new FileInfo(p));

                this.task = new UploadTask(files.ToArray());
                task.TaskComplated += task_TaskComplated;
                task.UploadStatusChanged += task_UploadStatusChanged;
                task.Start();
            }
        }

        void task_UploadStatusChanged(UploadTask sender, UploadFile file)
        {
            this.BeginInvoke(new Action(() =>
            {
                switch (file.UploadStatus)
                {
                    case E_FileUploadStatus.上传中:
                        this.label1.Text = string.Format("当前上传：{0}，当前进度：{1}%，总体进度：{2}/{3}，瞬时速度：{4}", file.File.Name, file.UploadProgress, sender.CurrentIndex, sender.TotalCount, sender.UploadSpeed);
                        break;
                    case E_FileUploadStatus.已完成:
                        this.Log(String.Format("{0}上传完成", file.File.Name));
                        break;
                    case E_FileUploadStatus.上传错误:
                        this.Log(String.Format("{0}上传错误，错误原因：{1}", file.File.Name, file.ErrorMessasge));
                        break;
                    case E_FileUploadStatus.已取消:
                        this.Log(String.Format("{0}上传已取消", file.File.Name));
                        break;
                    default:
                        break;
                }
            }));
        }

        private void Log(string message)
        {
            this.textBox1.AppendText(message + "\r\n");
        }

        void task_TaskComplated(UploadTask sender)
        {
            MessageBox.Show(this, "全部上传完成", "提示");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.task.Cancel();
        }
    }
}
